package org.jeecg.modules.exTenderFile.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.exPingbiao.entity.ExPingbiaoExpert;
import org.jeecg.modules.exPingbiao.entity.ExPingbiaoExpertDetail;
import org.jeecg.modules.exPingbiao.mapper.ExPingbiaoExpertDetailMapper;
import org.jeecg.modules.exPingbiao.mapper.ExPingbiaoExpertMapper;
import org.jeecg.modules.exTender.entity.ExTenderList;
import org.jeecg.modules.exTender.service.IExTenderListService;
import org.jeecg.modules.exTenderFile.entity.ExZbwjScoreStandardDetail;
import org.jeecg.modules.exTenderFile.entity.ScoreChapter;
import org.jeecg.modules.exTenderFile.mapper.ExZbwjScoreStandardDetailMapper;
import org.jeecg.modules.exTenderFile.mapper.ScoreChapterMapper;
import org.jeecg.modules.exTenderFile.service.IScoreChapterService;
import org.jeecg.modules.exTenderFile.vo.ScoreChapterTree;
import org.jeecg.modules.exTenderFile.vo.TenderScoreVO;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ScoreChapterServiceImpl extends ServiceImpl<ScoreChapterMapper, ScoreChapter> implements IScoreChapterService {

    @Autowired
    private ExZbwjScoreStandardDetailMapper scoreStandardDetailMapper;
    @Autowired
    private ExPingbiaoExpertMapper exPingbiaoExpertMapper;
    @Autowired
    private ExPingbiaoExpertDetailMapper exPingbiaoExpertDetailMapper;
    @Autowired
    private IExTenderListService tenderListService;

    @Override
    public void addSysCategory(ScoreChapter chapter) {
        String categoryCode = "";
        String categoryPid = ISysCategoryService.ROOT_PID_VALUE;
        String parentCode = null;
        if (oConvertUtils.isNotEmpty(chapter.getPid())) {
            categoryPid = chapter.getPid();

            //PID 不是根节点 说明需要设置父节点 hasChild 为1
            if (!ISysCategoryService.ROOT_PID_VALUE.equals(categoryPid)) {
                ScoreChapter parent = baseMapper.selectById(categoryPid);
                parentCode = parent.getCode();
                if (parent != null && !ISysCategoryService.HAS_CHILD.equals(parent.getHasChild())) {
                    parent.setHasChild(ISysCategoryService.HAS_CHILD);
                    baseMapper.updateById(parent);
                }
            }
        }
        //update-begin--Author:baihailong  Date:20191209 for：分类字典编码规则生成器做成公用配置
        JSONObject formData = new JSONObject();
        formData.put("pid", categoryPid);
        categoryCode = (String) FillRuleUtil.executeRule(FillRuleConstant.SCORE_CHAPTER, formData);
        //update-end--Author:baihailong  Date:20191209 for：分类字典编码规则生成器做成公用配置
        chapter.setCode(categoryCode);
        chapter.setPid(categoryPid);
        baseMapper.insert(chapter);
    }

    @Override
    public void updateSysCategory(ScoreChapter chapter) {
        if (oConvertUtils.isEmpty(chapter.getPid())) {
            chapter.setPid(ISysCategoryService.ROOT_PID_VALUE);
        } else {
            //如果当前节点父ID不为空 则设置父节点的hasChild 为1
            ScoreChapter parent = baseMapper.selectById(chapter.getPid());
            if (parent != null && !ISysCategoryService.HAS_CHILD.equals(parent.getHasChild())) {
                parent.setHasChild(ISysCategoryService.HAS_CHILD);
                baseMapper.updateById(parent);
            }
        }
        baseMapper.updateById(chapter);
    }

    @Override
    public List<TreeSelectModel> queryListByCode(String pcode) throws JeecgBootException {
        String pid = ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(pcode)) {
            List<ScoreChapter> list = baseMapper.selectList(new LambdaQueryWrapper<ScoreChapter>().eq(ScoreChapter::getCode, pcode));
            if (list == null || list.size() == 0) {
                throw new JeecgBootException("该编码【" + pcode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new JeecgBootException("该编码【" + pcode + "】存在多个，请核实!");
            }
            pid = list.get(0).getId();
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<TreeSelectModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<TreeSelectModel> queryListByPid(String pid, Map<String, String> condition) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, condition);
    }

    @Override
    public String queryIdByCode(String code) {
        return baseMapper.queryIdByCode(code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysCategory(String ids) {
        String allIds = this.queryTreeChildIds(ids);
        String pids = this.queryTreePids(ids);
        //1.删除时将节点下所有子节点一并删除
        this.baseMapper.deleteBatchIds(Arrays.asList(allIds.split(",")));
        //2.将父节点中已经没有下级的节点，修改为没有子节点
        if (oConvertUtils.isNotEmpty(pids)) {
            LambdaUpdateWrapper<ScoreChapter> updateWrapper = new UpdateWrapper<ScoreChapter>()
                    .lambda()
                    .in(ScoreChapter::getId, Arrays.asList(pids.split(",")))
                    .set(ScoreChapter::getHasChild, "0");
            this.update(updateWrapper);
        }
    }

    /**
     * 查询节点下所有子节点
     *
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if (pidVal != null) {
                if (!sb.toString().contains(pidVal)) {
                    if (sb.toString().length() > 0) {
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal, sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 查询需修改标识的父节点ids
     *
     * @param ids
     * @return
     */
    private String queryTreePids(String ids) {
        StringBuffer sb = new StringBuffer();
        //获取id数组
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            if (id != null) {
                ScoreChapter category = this.baseMapper.selectById(id);
                //根据id查询pid值
                String metaPid = category.getPid();
                //查询此节点上一级是否还有其他子节点
                LambdaQueryWrapper<ScoreChapter> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ScoreChapter::getPid, metaPid);
                queryWrapper.notIn(ScoreChapter::getId, Arrays.asList(idArr));
                List<ScoreChapter> dataList = this.baseMapper.selectList(queryWrapper);
                boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(metaPid)
                        && !sb.toString().contains(metaPid);
                if (flag) {
                    //如果当前节点原本有子节点 现在木有了，更新状态
                    sb.append(metaPid).append(",");
                }
            }
        }
        if (sb.toString().endsWith(SymbolConstant.COMMA)) {
            sb = sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    /**
     * 递归 根据父id获取子节点id
     *
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal, StringBuffer sb) {
        LambdaQueryWrapper<ScoreChapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ScoreChapter::getPid, pidVal);
        List<ScoreChapter> dataList = baseMapper.selectList(queryWrapper);
        if (dataList != null && dataList.size() > 0) {
            for (ScoreChapter category : dataList) {
                if (!sb.toString().contains(category.getId())) {
                    sb.append(",").append(category.getId());
                }
                this.getTreeChildIds(category.getId(), sb);
            }
        }
        return sb;
    }

    @Override
    public List<String> loadDictItem(String ids) {
        return this.loadDictItem(ids, true);
    }

    @Override
    public List<String> loadDictItem(String ids, boolean delNotExist) {
        String[] idArray = ids.split(",");
        LambdaQueryWrapper<ScoreChapter> query = new LambdaQueryWrapper<>();
        query.in(ScoreChapter::getId, Arrays.asList(idArray));
        // 查询数据
        List<ScoreChapter> list = super.list(query);
        // 取出name并返回
        List<String> textList;
        // update-begin--author:sunjianlei--date:20210514--for：新增delNotExist参数，设为false不删除数据库里不存在的key ----
        if (delNotExist) {
            textList = list.stream().map(ScoreChapter::getName).collect(Collectors.toList());
        } else {
            textList = new ArrayList<>();
            for (String id : idArray) {
                List<ScoreChapter> res = list.stream().filter(i -> id.equals(i.getId())).collect(Collectors.toList());
                textList.add(res.size() > 0 ? res.get(0).getName() : id);
            }
        }
        // update-end--author:sunjianlei--date:20210514--for：新增delNotExist参数，设为false不删除数据库里不存在的key ----
        return textList;
    }

    @Override
    public List<ScoreChapterTree> treeList(String expertId, String businessId, String scoreStandardId, String standardType,String tenderId) {
        LambdaQueryWrapper<ScoreChapter> query = new LambdaQueryWrapper<ScoreChapter>().eq(ScoreChapter::getScoreStandardId, scoreStandardId).eq(ScoreChapter::getStandardType, standardType);
        List<ScoreChapter> scoreChapterList = this.list(query);

        List<ScoreChapterTree> scoreChapterTreeList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(scoreChapterList)) {
            List<ExZbwjScoreStandardDetail> standardDetailList = scoreStandardDetailMapper.selectByBusinessIdList(scoreChapterList.stream().map(ScoreChapter::getId).collect(Collectors.toList()));
            Map<String, ExZbwjScoreStandardDetail> standardDetailMap = Maps.newHashMap();
            for (ExZbwjScoreStandardDetail standardDetail : standardDetailList) {
                if (!standardDetailMap.containsKey(standardDetail.getCategoryId())) {
                    standardDetailMap.put(standardDetail.getCategoryId(), standardDetail);
                }
            }

            for (ScoreChapter scoreChapter : scoreChapterList) {
                ScoreChapterTree scoreChapterTree = new ScoreChapterTree();
                BeanUtils.copyProperties(scoreChapter, scoreChapterTree);
                ExZbwjScoreStandardDetail standardDetail = standardDetailMap.get(scoreChapter.getId());
                if (null != standardDetail) {
                    scoreChapterTree.setIndicatorName(standardDetail.getIndicatorName());
                    scoreChapterTree.setIndicatorType(standardDetail.getIndicatorType());
                    scoreChapterTree.setScore(standardDetail.getScore());
                    scoreChapterTree.setScoreMin(standardDetail.getScoreMin());
                    scoreChapterTree.setScoreMax(standardDetail.getScoreMax());
                    scoreChapterTree.setWeight(standardDetail.getWeight());
                    scoreChapterTree.setDescription(standardDetail.getDescription());
                }
                scoreChapterTreeList.add(scoreChapterTree);
            }
        }
        if (StringUtils.isNotBlank(expertId) && StringUtils.isNotBlank(businessId)) {
            List<ExPingbiaoExpert> pingbiaoExpertList = exPingbiaoExpertMapper.selectByExpertIdAndBusinessIdList(expertId, com.google.common.collect.Lists.newArrayList(businessId));
            pingbiaoExpertList = pingbiaoExpertList.stream().filter(e -> Objects.equals(tenderId, e.getTenderListId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(pingbiaoExpertList)) {
                List<ExPingbiaoExpertDetail> expertDetailList = exPingbiaoExpertDetailMapper.selectByExpertAndBusinessId(pingbiaoExpertList.get(0).getId(), "评分标准");
                Map<String, BigDecimal> scoreMap = expertDetailList.stream().collect(Collectors.toMap(ExPingbiaoExpertDetail::getBusinessId, ExPingbiaoExpertDetail::getScore));
                for (ScoreChapterTree scoreChapterTree : scoreChapterTreeList) {
                    scoreChapterTree.setExpertScore(scoreMap.get(scoreChapterTree.getId()));
                }
            }

        }
        List<ScoreChapterTree> treeList = Lists.newArrayList();
        getTreeList(treeList, scoreChapterTreeList, null);
        return treeList;
    }

    private void getTreeList(List<ScoreChapterTree> treeList, List<ScoreChapterTree> metaList, ScoreChapterTree temp) {
        for (ScoreChapterTree scoreChapterTree : metaList) {
            String tempPid = scoreChapterTree.getPid();
            ScoreChapterTree tree = new ScoreChapterTree();
            BeanUtils.copyProperties(scoreChapterTree, tree);
            ;
            if (temp == null && (oConvertUtils.isEmpty(tempPid) || "0".equals(tempPid))) {
                treeList.add(tree);
                if ("1".equals(tree.getHasChild())) {
                    getTreeList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
                if (null == temp.getChildren()) {
                    temp.setChildren(Lists.newArrayList());
                }
                temp.getChildren().add(tree);
                if ("1".equals(tree.getHasChild())) {
                    getTreeList(treeList, metaList, tree);
                }
            }
        }
    }

    @Override
    public List<ScoreChapterTree> queryTenderTreeList(String expertId, String businessId, String scoreStandardId, String standardType) {
        LambdaQueryWrapper<ScoreChapter> query = new LambdaQueryWrapper<ScoreChapter>().eq(ScoreChapter::getScoreStandardId, scoreStandardId).eq(ScoreChapter::getStandardType, standardType);
        List<ScoreChapter> scoreChapterList = this.list(query);

        List<ScoreChapterTree> scoreChapterTreeList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(scoreChapterList)) {
            List<ExZbwjScoreStandardDetail> standardDetailList = scoreStandardDetailMapper.selectByBusinessIdList(scoreChapterList.stream().map(ScoreChapter::getId).collect(Collectors.toList()));
            Map<String, ExZbwjScoreStandardDetail> standardDetailMap = Maps.newHashMap();
            for (ExZbwjScoreStandardDetail standardDetail : standardDetailList) {
                if (!standardDetailMap.containsKey(standardDetail.getCategoryId())) {
                    standardDetailMap.put(standardDetail.getCategoryId(), standardDetail);
                }
            }
            for (ScoreChapter scoreChapter : scoreChapterList) {
                ScoreChapterTree scoreChapterTree = new ScoreChapterTree();
                BeanUtils.copyProperties(scoreChapter, scoreChapterTree);
                ExZbwjScoreStandardDetail standardDetail = standardDetailMap.get(scoreChapter.getId());
                if (null != standardDetail) {
                    scoreChapterTree.setIndicatorName(standardDetail.getIndicatorName());
                    scoreChapterTree.setIndicatorType(standardDetail.getIndicatorType());
                    scoreChapterTree.setScore(standardDetail.getScore());
                    scoreChapterTree.setScoreMin(standardDetail.getScoreMin());
                    scoreChapterTree.setScoreMax(standardDetail.getScoreMax());
                    scoreChapterTree.setWeight(standardDetail.getWeight());
                    scoreChapterTree.setDescription(standardDetail.getDescription());
                }
                scoreChapterTreeList.add(scoreChapterTree);
            }
        }
        if (StringUtils.isNotBlank(expertId) && StringUtils.isNotBlank(businessId)) {
            List<ExPingbiaoExpert> pingbiaoExpertList = exPingbiaoExpertMapper.selectByExpertIdAndBusinessIdList(expertId, com.google.common.collect.Lists.newArrayList(businessId));
            if (CollectionUtils.isNotEmpty(pingbiaoExpertList)) {
                // 构建投标人map
                Map<String,String> tenderIdMap= pingbiaoExpertList.stream().collect(Collectors.toMap(ExPingbiaoExpert::getId,ExPingbiaoExpert::getTenderListId));
                // 查询投标人名称
                Set<String> tenderListIdList = pingbiaoExpertList.stream().map(ExPingbiaoExpert::getTenderListId).collect(Collectors.toSet());
                List<ExTenderList> tenderList = tenderListService.getBaseMapper().selectBatchIds(tenderListIdList);
                Map<String, String> tenderNameMap = tenderList.stream().collect(Collectors.toMap(ExTenderList::getId, ExTenderList::getBidderName));
                // 查询投标明细
                List<String> expertIdList = pingbiaoExpertList.stream().map(ExPingbiaoExpert::getId).collect(Collectors.toList());
                LambdaQueryWrapper<ExPingbiaoExpertDetail> detailQuery = new LambdaQueryWrapper<ExPingbiaoExpertDetail>().in(ExPingbiaoExpertDetail::getPingbiaoExpertId, expertIdList)
                        ;
                List<ExPingbiaoExpertDetail> detailList = exPingbiaoExpertDetailMapper.selectList(detailQuery);
                if(CollectionUtils.isNotEmpty(detailList)){
                    List<TenderScoreVO> tenderScoreList = detailList.stream().map(e -> {
                        TenderScoreVO tenderScoreVO = new TenderScoreVO();
                        tenderScoreVO.setId(tenderIdMap.get(e.getPingbiaoExpertId()));
                        tenderScoreVO.setName(tenderNameMap.get(tenderScoreVO.getId()));
                        tenderScoreVO.setBusinessId(e.getBusinessId());
                        tenderScoreVO.setScore(e.getScore());
                        return tenderScoreVO;
                    }).collect(Collectors.toList());
                    Map<String,List<TenderScoreVO>> businessTenderScoreMap = tenderScoreList.stream().collect(Collectors.groupingBy(TenderScoreVO::getBusinessId));
                    List<ExPingbiaoExpertDetail> expertDetailList = exPingbiaoExpertDetailMapper.selectByExpertAndBusinessId(pingbiaoExpertList.get(0).getId(), "评分标准");
                    Map<String, BigDecimal> scoreMap = expertDetailList.stream().collect(Collectors.toMap(ExPingbiaoExpertDetail::getBusinessId, ExPingbiaoExpertDetail::getScore));
                    for (ScoreChapterTree scoreChapterTree : scoreChapterTreeList) {
                        List<TenderScoreVO> testList = businessTenderScoreMap.getOrDefault(scoreChapterTree.getId(), Lists.newArrayList());
                        scoreChapterTree.setExpertScore(scoreMap.get(scoreChapterTree.getId()));
                        scoreChapterTree.setScoreList(testList);
                    }
                }

            }

        }
        List<ScoreChapterTree> treeList = Lists.newArrayList();
        getTreeList(treeList, scoreChapterTreeList, null);
        return treeList;
    }
}
